#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <signal.h>

#include "include_all.h"
#include "tool_watchdog.h"
#include "thread_listen.h"
#include "thread_broadcast.h"

static struct watchdog_info watchdog;

void signal_handle(int signo)
{
	if(watchdog.run_get(RT_INITOK) > 0)
	{
		printf("\n########################################################################\nThis program will be exit as soon as possible, Please wait a moment...\n########################################################################\n\n");
		watchdog.run_unreg(RT_INITOK);
	}
	else
	{
		printf("Please wait...\n");
		return;
	}
}

int main(int argc, char **argv)
{
	if(argc > 1)
	{
		printf("Too many argument\n");
		return RET_FAIL;
	}

	if(STATISTICS_INTERVAL < 1 || BROADCASE_INTERVAL < 1 || TCP_PORT < 0 || TCP_PORT > 65535 || BROADCASE_PORT < 0 || BROADCASE_PORT >65535)
	{
		printf("Define failed\n");
		return RET_FAIL;
	}

	memset(&watchdog, 0, sizeof(struct watchdog_info));

	if(watchdog_init(&watchdog) != RET_OK)
	{
		printf("%s: watchdog_init failed\n", __func__);
		return RET_FAIL;
	}

	if(listen_init(&watchdog, TCP_PORT) != RET_OK)
	{
		printf("%s: listen_init failed\n", __func__);
		return RET_FAIL;
	}

	if(broadcase_init(&watchdog, BROADCASE_PORT) != RET_OK)
	{
		printf("%s: broadcase_init failed\n", __func__);
		return RET_FAIL;
	}

	signal(SIGINT, signal_handle);
	signal(SIGQUIT, signal_handle);
	signal(SIGUSR1, signal_handle);
	signal(SIGUSR2, signal_handle);

	watchdog.run_reg(0);

	printf("Init OK\n");

	while(watchdog.run_get(0) > 0)
	{
#if DEBUG
		printf("run table: %d\n", watchdog.runtable);
#endif
		sleep(STATISTICS_INTERVAL);
	}

	while(watchdog.runtable > 0)
	{
		printf("Please wait, now remainder: %d\n", watchdog.runtable);
		usleep(500000);
	}

	printf("\n\t####################\n\t###   Good Bye   ###\n\t####################\n\n");
	return RET_OK;
}